<?php
class CommonAction extends Action {
    public $dao;
    public $listmap = 1;
    public $listorder = 'id DESC';
    public $pagesize = 20;
	//设置缩略图最大宽度
    public $thumbMaxWidth = 500;
        //设置缩略图最大高度
    public $thumbMaxHeight = 500;
    function _initialize() {
        if(isset($_GET['jumpUrl']) && $_GET['jumpUrl'] != ''){
			session('jumpUrl', $_GET['jumpUrl']);
		}
		header("content-type:text/html; charset=utf-8;");
        //Rbac检测
        if (C('USER_AUTH_ON') && !in_array(MODULE_NAME, explode(',', C('NOT_AUTH_MODULE')))) {
            import('@.ORG.RBAC');
            if (!RBAC::AccessDecision(GROUP_NAME)) {
                //检查认证识别号
                if (!session(C('USER_AUTH_KEY'))) {
					
                    //跳转到认证网关
					if(C('URL_MODEL') == 2){
				         $jumpUrl = str_replace('index.php/','',__SELF__);
			        }else{
				         $jumpUrl = __SELF__;
			        }
			        session('jumpUrl',$jumpUrl);
					session('siteid', cookie('siteid'));
					
					$nologin['info'] = '登录超时，请重新登录！';
					$nologin['status'] = 408;
					if(IS_AJAX){
						exit(json_encode($nologin));
					}
					
					
                    redirect(U(C('USER_AUTH_GATEWAY')));
                }
                // 没有权限 抛出错误 
                if (C('RBAC_ERROR_PAGE')) {
                    // 定义权限错误页面
                    redirect(C('RBAC_ERROR_PAGE'));
                } else {
                    if (C('GUEST_AUTH_ON')) {
						
                        $this->assign('jumpUrl', U(C('USER_AUTH_GATEWAY')));
                    }
                    // 提示错误信息
                    $this->error(L('_VALID_ACCESS_'));
                }
            }
        }
		$this->accessList = RBAC::getAccessList(session(C('USER_AUTH_KEY')));
        //sitemapxml();
        //实现列表排序
        if ($this->_get('sortField')) {
            $this->listorder = $this->_get('sortField');
            $this->assign('sortField', $this->_get('sortField'));
        }
        if ($this->_get('sortType')) {
            if($this->_get('sortField') && $this->_get('sortField') != ''){
			     $this->listorder.= " " . $this->_get('sortType');
			}
            if ($this->_get('sortType') == '' || $this->_get('sortType') == 'ASC') {
                $this->assign('sortType', 'DESC');
            } else {
                $this->assign('sortType', 'ASC');
            }
        }else{
			if($this->_get('sortField') && $this->_get('sortField') != ''){
			     $this->listorder.= " " . $this->_get('sortType');
			}
            if ($this->_get('sortType') == '' || $this->_get('sortType') == 'ASC') {
                $this->assign('sortType', 'DESC');
            } else {
                $this->assign('sortType', 'ASC');
            }
		}
        //实现列表分页条数
        if ($this->_get('pagesize')) {
            $this->pagesize = intval($this->_get('pagesize'));
            $this->assign('pagesize', $this->pagesize);
        }
        $this->UserInfo = session(C('USER_AUTH_KEY'));
        //渲染顶部操作菜单项
        $this->left_menu = $this->createMenu();
        //从列表中对比确定是否存在表，创建相应的数据对象
        $Mode_list = array(
            'access',
            'adv',
            'guestbook',
            'news',
            'node',
            'reply',
            'role',
            'user',
            'setting',
            'category',
            'menugroup',
            'module',
            'role_user',
            'weixin_menu',
            'site',
            'setting_group',
            'template',
            'template_group',
            'product_category',
            'type',
            'attr',
            'attr_val',
            'product',
            'nav',
            'member',
            'member_group',
            'info',
            'order',
			'img',
			'imgcate',
			'infocategory',
            'integral_rule',
            'integral_ruletype',
			'magic',
			'magicuseraddnumber',
			'examination',
			'manage_module',
			'modules',
			'template_modules',
			'mission',
			'field',
			'form',
			'server',
			'shop',
			'brand',
			'pages',
			'modules_category',
			'pagescate',
			'langs',
			'langconfig',
			'member_account_log',
            'member_group',
			'member_position',
            'member_role_user',
            'member_access',
            'integral_log',
            'member_bank',
			'affiliatesetting',
			'affiliatelog',
			'payment',
			'supplier',
			'shipping',
			'bargain',
			'invoice',
			'subscribe',
			'evaluate',
			'systempages',
			'brand',
			'grouppurchase',
			'cashback_count',
            'cashback_config',
            'cashback_log',
            'coupon',
            'coupon_sn',
			'servicecard',
			'style',
			'systempackage',
			'collectcategory',
			'collect',
			'site_balance_log',
			'agentlevel',
			'agentprice',
			'shippingregion',
			'formcategory'
        );
        if (in_array(strtolower(MODULE_NAME) , $Mode_list)) {
            $this->dao = D(MODULE_NAME);
        }
        //如果是超级管理员,则列出所有站点
		//dump(__SITEID__);
        //dump(session(C ( 'ADMIN_AUTH_KEY' )));
        if (session(C('ADMIN_AUTH_KEY'))) { 
            $this->site_list = M("Site")->select();
        } else {
            $this->site_list = D("Site")->getSite_list($this->UserInfo);
        }
        //列出站点后写一个session标出当前管理的站点
        if (isset($_GET['siteid']) && intval($_GET['siteid']) > 0) {
            $istrue = D("Site")->getManage($this->UserInfo,intval($_GET['siteid']));
            
            if (session(C('ADMIN_AUTH_KEY')) || $istrue) {
                session('siteid', $_GET['siteid']);
                $this->siteid = session('siteid');
            }else{
				$this->error('您没有管理权限');
			}
        }
		
		//dump(session('siteid'));
        $this->siteid = '0';
        $this->siteid = session('siteid') ? session('siteid') : $this->site_list[0]['id'];
        if (!$this->siteid) {
            $this->siteid = 0;
        }
		
		//dump(defined('__SITEID__'));
		if(!isset($_GET['siteid']) && !session('siteid')){
			
			
			
			if(C('URL_MODEL') == 2){
				         $jumpUrl = str_replace('index.php/','',__SELF__);
			        }else{
				         $jumpUrl = __SELF__;
			        }
			
			//$_GET['siteid'] = $this->siteid;
			
			redirect($jumpUrl.'?siteid='.$this->siteid);
		}
		
		
        //exi$this->siteidt($this->siteid);
        //设置当前站点ID常量
        //dump($this->siteid);
        //dump(M("Setting_extends")->select());
        $_POST['site_id'] = $this->siteid; //每个表要写入siteid，提前设定
		define('__ADMINSITEID__',$this->siteid);
		
		//dump(__ADMINSITEID__);
		
		
        $this->listmap.= " and site_id=" . $this->siteid;
        //记录当前访问路径
        //模块
        $moduleOne = M('Node')->where(array(
            'name' => MODULE_NAME,
            'level' => 2
        ))->find();
        $this->assign('moduleOne', $moduleOne);
        //操作
        $actionOne = M('Node')->where(array(
            'name' => ACTION_NAME,
            'pid' => $moduleOne['id']
        ))->find();
        $this->assign('actionOne', $actionOne);
		
		if(ACTION_NAME == 'index'){
			if(C('URL_MODEL') == 2){
				$jumpUrl = str_replace('index.php/','',__SELF__);
			}else{
				$jumpUrl = __SELF__;
			}
			session('jumpUrl',$jumpUrl);
		}
		
		//标识site_id ,防止退出后重新登录丢失参数
		cookie('site_id', $this->siteid, 72000);
		$sdb = M('Site');
		//关联站点列表
		//是否关联数据
		$site = M('Site') -> where(array('id' => $this->siteid)) -> find();
		if($site['synchronous'] == 1){
			$this->assign('relateSiteList',$sdb->where(array('relate_id' => $this->siteid))->select());
		}
		
		//查找关联站点数据
		if($this->_get('relate_id') && $this->_get('site_id')){
			$relatedata = $this->dao -> where(array('site_id' => $this->_get('site_id'),'relate_id' => $this->_get('relate_id'))) -> find();
			
			if(!$relatedata){
				$this->insert_data = $this->dao -> where(array('id' => $this->_get('relate_id')))->find();
			    $this->insert_relate();
				$relatedata = $this->dao -> where(array('site_id' => $this->_get('site_id'),'relate_id' => $this->_get('relate_id'))) -> find();
			}
			$this->siteid = $this->_get('site_id');
			$_GET['id'] = $relatedata['id'];
		}
		$this->assign(getLangConf($this->siteid));
		
		
		
		if(strtolower(ACTION_NAME) == 'index'){
			$loadIndexUrl = '';
			if(C('URL_MODEL') == 2){
				 $loadIndexUrl = str_replace('index.php/','',__SELF__);
			}else{
				 $loadIndexUrl = __SELF__;
			}
			$per = $_REQUEST;
			unset($per['_URL_']);
			unset($per['theme']);
			unset($per['p']);
			
			//session(MODULE_NAME, $per);
			
			setcookie('loadIndexUrl', U('index', $per), time() + 3600, '/');
		}
		
    }
    
	public function display($temp = ''){
			if(IS_AJAX){
				$list = $_GET['list'];
				//$list = $this->fetch();
				$empty = 1;
				$statu=$list?1:0;
				if($this->get('list')){
					$empty = 0;
				}
                $this->initView();
			    die(json_encode(array('empty' => $empty,'tbody'=>$this->fetch($temp),'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this->view->get('pages'))));
			}else{
				parent::display($temp);
			} 

	}
	
	
	
	
	
	
    //显示添加页
    public function add() {
        $this->display();
    }
    //显示修改页
    public function edit($temp = '') {
        if ($this->_get('id')) {
            $map['id'] = array(
                'eq',
                $this->_get('id')
            );
            $this->info = $this->dao->where($map)->find();
            $this->display($temp);
        } else {
            $this->error('参数错误');
        }
    }
    //写入数据
    public function insert($data = '', $jumpUrl = '') {
		if($jumpUrl == ''){
			$jumpUrl = (session('jumpUrl')&&session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
		}
        
        if ($this->dao->create($data)) {
            $result = $this->dao->add();
            if (false !== $result) {
				if(strtolower(MODULE_NAME) != 'site'){
				  $this->insert_data = $this->dao->where(array('id' => $result))->find();
				  $this->insert_relate();
				}
				
                $this->success('操作成功', $jumpUrl);
            } else {
                $this->error($this->dao->getError());
            }
        } else {
            $this->error($this->dao->getError());
        }
    }
    public function _list($rename = '', $join = '', $field='') {
        $map = $this->listmap;
		
		$order = $this->listorder;
        $pagesize = $this->pagesize;
		
        //计算总页数
        if ($join != '' || $rename != '') { //链接查询

            $count = $this->dao->alias($rename)->join($join)->where($map)->count();

            import('ORG.Util.Page');
            //实例化分页类
			
            $p = new Page($count, $pagesize);
            $this->list = $this->dao->alias($rename)->join($join)->where($map)->order($order)->Field($field)->limit($p->firstRow . ',
	' . $p->listRows)->select();
            $this->pages = $p->show();
        } else {
            $count = $this->dao->where($map)->count();
            import('ORG.Util.Page');
            //实例化分页类
            $p = new Page($count, $pagesize);
            $this->list = $this->dao->where($map)->order($order)->limit($p->firstRow . ',
	' . $p->listRows)->select();
            $this->pages = $p->show();
        }
    }
    //删除记录
    public function delete() {
			$jumpUrl = (session('jumpUrl')&& session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
        if ($this->_get('id')) {
            $map['id'] = array(
                'in',
                $this->_get('id')
            );
            $result = $this->dao->where($map)->delete();
            //dump();
            if (false !== $result) {
                $this->success('删除成功!', $jumpUrl);
            } else {
                $this->error('操作失败！');
            }
        }
    }
    //通用文件上传
    public function _upload($file = 'file') {
        import("ORG.Net.UploadFile");
        $upload = new UploadFile(); 
        //设置上传文件大小
        $upload->maxSize = 3*1024*1024;
        $upload->allowExts = explode(',', C('UPLOAD_EXTS'));
        $upload->savePath = "./Public/Uploads/".$this->siteid.'/'. MODULE_NAME . "" . $this->siteid . "-";
        //自动命名
        $upload->saveRule = 'uniqid';
		
		if($this->_post('rewrite')){
			$upload->saveRule = pathinfo($this->_post('rewrite'),PATHINFO_FILENAME);
	    }
        //创建目录
        $upload->savePath = $upload->savePath . date('Ymd', time()) . "/";
        if (!file_exists("$upload->savePath")) {
            mk_dir($upload->savePath);
        }
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = 1;
        //设置需要生成缩略图的文件后缀
        //$upload->thumbSuffix = "_thumb";
        //设置缩略图最大宽度
        $upload->thumbMaxWidth = $this->thumbMaxWidth;
        //设置缩略图最大高度
        $upload->thumbMaxHeight = $this->thumbMaxHeight;
        $upload->uploadReplace = true;
        if (!$upload->upload()) {
            $error = $upload->getErrorMsg();
            exit($error);
            return false;
        } else {
            $uploadSuccess = true;
            $uploadList = $upload->getUploadFileInfo();
			//路径入库
			$imgdata['img_url'] = '/' . trim($uploadList[0]['savepath'], './Public') . '/' . $uploadList[0]['savename'];
			$imgdata['site_id'] = $this->siteid;
			$imgdata['size'] = $uploadList[0]['size'];
			$imgdata['user_id'] = session(C('USER_AUTH_KEY') );
			$imgdata['cate_id'] = $this->_get('cate_id')?$this->_get('cate_id'):0;
			M('Img')->data($imgdata)->add();
            return '/' . trim($uploadList[0]['savepath'], './Public') . '/' . $uploadList[0]['savename'];
        }
    }
    //单文件上传
    public function upload() {
        if (isset($_FILES['file'])) {
            $this->name = isset($_POST['name']) ? $_POST['name'] : 'img_url';
            $info = $this->_upload('file');
            //dump($info);exit();
            if ($this->name != 'img_url') {
                exit("<script>window.parent.uploaded" . $this->name . "('" . $info . "','" . $this->name . "'); location.href='" . U('upload', array(
                    'name' => $this->name
                )) . "';</script>");
            } else {
                exit("<script>window.parent.uploaded('" . $info . "'); location.href='" . U('upload') . "';</script>");
            }
        } else {
            $this->name = $this->_get('name');
			if($this->name == ''){
				$this->assign('name', 'img_url');
			}
            $this->display('Public:upload');
        }
    }
	
	//单文件上传
    public function uploadimg() {

            $this->name = isset($_POST['name']) ? $_POST['name'] : 'img_url';
            $info = $this->_upload('file');
            //dump($info);exit();
            echo $info;
        
    }
	
	
    //这是更新数据
    public function update($data = array() , $jumpUrl = '') {
        if($jumpUrl == ''){
			$jumpUrl = ( session('jumpUrl') && session('jumpUrl') != '') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
		}
        if ($this->_post('id')) {
            unset($_POST['site_id']);
            $map['id'] = array(
                'eq',
                $this->_post('id')
            );
            if (!empty($data)) {
                if (!$this->dao->create($data)) {
                    $this->error($this->dao->getError());
                }
            } else {
                if (!$this->dao->create()) {
                    $this->error($this->dao->getError());
                }
            }
            //dump($data);exit();
            //dump(I('post.'));exit();
            $result = $this->dao->save();
            //echo $this->dao->getLastSql();exit();
            if (false !== $result) {
				if($jumpUrl == 'closeModel'){
					exit('<script>window.parent.closeModel();</script>');
				}
                $this->success('更新成功', $jumpUrl);
            } else {
                $this->error($this->dao->getError());
            }
        } else {
            $this->error('参数错误');
        }
    }
    //生成管理菜单
    protected function createMenu() {
        $group = M('Menugroup')->where(array(
            'status' => 1, 'typeid' => 0
        ))->order('sort')->select();
        $node = M('Node');
        if (session(C('ADMIN_AUTH_KEY') )) {
            foreach ($group as $k => $v) {
                $group[$k]['menu'] = $node->where(array(
                    'status' => 1,
                    'gid' => $v['id'],
                    'level' => 2
                ))->order('sort')->select();
            }
            return $group;
        } else {
            $menu = Rbac::getAccessList($this->UserInfo);
            $n = array();
            foreach ($menu['ADMIN'] as $kk => $vv) {
                $n[] = "'" . ucwords(strtolower($kk)) . "'";
            }
            $map = implode(',', $n);
			$ret = array();
            foreach ($group as $k => $v) {
                $list_menu = $node->where("status=1 and gid={$v['id']} and level=2 and name in($map)")->order('sort')->select();
                if (count($list_menu) > 0) {
                    $group[$k]['menu'] = $list_menu;
					$ret[] = $group[$k];
                } else {
                    unset($group[$k]);
                }
            }
            return $ret;
        }
    }
    //改变状态
    public function status() {
        if ($this->_post('id')) {
            $id = $this->_post('id');
            $one = $this->dao->where(array(
                'id' => $id
            ))->find();
            if (is_array($one)) {
                if ($one['status'] == 1) {
                    $data['status'] = 0;
                } else {
                    $data['status'] = 1;
                }
                //$this->dao->create($data);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save($data);
                if (false !== $re) {
                    exit($data['status']);
                } else {
                    exit('error');
                }
            } else {
                exit('error');
            }
        }
    }
    //改变排序
    public function dosort($m = '') {
		
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
			$m = $m == ''?MODULE_NAME:$m;
            $this->dao = M($m);
			//exit('asdfadsf');
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d[$this->_post('field') ] = intval($onearr[1]);
                //$this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save($d);
            }
            exit('OK');
        }
    }
    //改变图文列表推荐排序
    public function doRecSort() {
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d['is_rec'] = intval($onearr[1]);
                //$this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save($d);
            }
            exit('OK');
        }
    }
    //改变图文列表置顶排序
    public function doTopSort() {
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d['is_top'] = intval($onearr[1]);
                $this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save();
            }
            exit('OK');
        }
    }
    //改变图文列表热门排序
    public function doHotSort() {
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d['is_hot'] = intval($onearr[1]);
                $this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save();
            }
            exit('OK');
        }
    }
    //改变微信图文列表排序
    public function doweixin_sort() {
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d['weixin_sort'] = intval($onearr[1]);
                $this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save();
            }
            exit('OK');
        }
    }
    //多文件上传
    public function mupload() {
        $savepath = $this->_upload('Filedata');
        $data['status'] = 1;
        $data['info'] = '成功';
        $data['data'] = $savepath;
        echo json_encode($data);
    }
    //删除一张图片
    public function delImgBypath($mpath = '') {
        if ($this->_post('path')) {
            $fpath = './Public' . $this->_post('path');
            //if (is_file($fpath)) {
                $re = @unlink($fpath);
                @unlink(getThumbPath($fpath));
				//从数据库中删除
				M('Img')-> where(array('site_id' => $this->siteid, 'img_url' => $this->_post('path')))->delete();
                if ($re !== false) {
                    exit('OK');
                } else {
                    exit($fpath);
                }
            //} else {
//                exit('error');
//            }
        } else {
            $fpath = './Public' . $mpath;
            if (is_file($fpath)) {
                $re = @unlink($fpath);
                @unlink(getThumbPath($fpath));
                //exit($fpath);
                if ($re !== false) {
					M('Img')-> where(array('site_id' => $this->siteid, 'img_url' => $mpath))->delete();
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    }
    //异步更新单个字段内容
    public function ajaxUpdate(){
        if ($this->_post('data')) {
            $data = explode(',', $this->_post('data'));
            $id = $data[1];
            $field = $data[0];
            $returndata = array();
            $one = $this->dao->where(array(
                'id' => $id
            ))->find();
            if (!is_array($one)) {
                $returndata['status'] = 0;
            } else {
                if ($one[$field] == 0) {
                    $savedate[$field] = 1;
                } else {
                    $savedate[$field] = 0;
                }
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save($savedate);
                if ($re !== false) {
                    $returndata['status'] = 1;
                } else {
                    $returndata['status'] = 0;
                }
            }
        } else {
            $returndata['status'] = 0;
        }
        $returndata['data'] = $savedate[$field];
        echo json_encode($returndata);
    }
	
	// ajax更新字段
	public function ajaxText(){
		$table = str_replace(C('DB_PREFIX'),'',$this->_post('tablename'));
		$field = $this->_post('field');
		$id = $this->_post('id');
		$val = $this->_post('val');
		$db = M($table);
		if($table == 'nav'){
		   if($field == 'link'){
			 if(!(substr($val,0,7) == 'http://' || substr($val,0,8) == 'https://' || substr($val,0,7) == 'mailto:' || substr($val,0,4) == 'tel:')){
				 $val = "__APP__".$val;
			 }
		   }
		}
		$ret = $db -> where(array('id' => $id)) -> data(array($field => $val)) -> save();
		if($ret !== false){
			$re['status'] = 1;
			$re['data'] = $val;
			$re['info'] = '更新成功';
		}else{
			$re['status'] = 0;
			$re['data'] = $val;
			$re['info'] = $db -> getError();
		}
		echo json_encode($re);
	}
	
    public function clearCache() {
        if (clearCache($this->siteid)) {
			$siteids = M('Site')-> where(array('relate_id' => $this->siteid)) -> select();
			foreach($siteids as $v){
				clearCache($v['id']);
			}
            $this->success('成功清除缓存!');
        } else {
            $this->error('清除缓存失败!');
        }
    }
    //裁剪图片
	public function cropImg($url = ''){
		//图片裁剪数据
		if($url == ''){
			$url = '.'.$this->_post('src');
		}
		$params = $this->_post();						//裁剪参数
		if(!isset($params) && empty($params)){
			return;
		}
		//临时图片地址
		$pic_path = $path.$params['picName']; 
		import('ORG.ThinkImage.ThinkImage'); 
		$Think_img = new ThinkImage(THINKIMAGE_GD);
		//裁剪原图
		$Think_img->open($url)->crop($params['w'],$params['h'],$params['x'],$params['y'])->save($url);
		$Think_img->open($url)->thumb(300,300, 1)->save(getThumbPath($url));
		$this->success('操作成功',U('Img/imagesBox'));
	}
	
	
	
	//如果存在关联站点，生成关联站点的数据
	public function insert_relate($dao = ''){
		$site = M('Site') -> where(array('id' => $this->siteid)) -> find();
		if($site['synchronous'] == 0){
			return false;
		}
		if($dao != ''){
			$this->dao = D($dao);
		}
		
		//是否有关联站点
		//是否存在关联ID的字段
		$fieldList = $this->dao -> getDbFields();
		if(in_array('relate_id',$fieldList)){
			$siteDB = M('Site');
			$sitelist = $siteDB -> where(array('relate_id' => $this->siteid)) -> select();
			if(is_array($sitelist)){
				$data = $this->insert_data;
				unset($data['id']);
				$data['relate_id'] = $this->insert_data['id'];
				
				foreach($sitelist as $k => $v){
					//存在PID字段
					$data['site_id'] = $v['id'];
					if(in_array('pid',$fieldList) && $this->insert_data['pid'] > 0){
						$pid = $this->dao -> where(array('site_id' => $v['id'],'relate_id' => $this->insert_data['pid'])) -> find();
						$data['pid'] = $pid['id'];
					}
					if(in_array('category_id',$fieldList) && $this->insert_data['category_id'] > 0){
						if(strtolower(MODULE_NAME) == 'category'){
						    $cateDb = M('Category');
						}else{
							$cateDb = M('Product_category');
						}
						$pid = $cateDb -> where(array('site_id' => $v['id'],'relate_id' => $this->insert_data['category_id'])) -> find();
						$data['category_id'] = intval($pid['id']);
					} 
					$this->dao -> data($data) -> add();
				}
			}
		}
	}
	
	
	public function getRegion(){
		$father_id = isset($_POST['fid'])?intval($_POST['fid']):0;
		$db=M('Region');
		$data = $db->where(array('father_id'=>$father_id))->select();
		$str = '<option value="">-请选择-</option>';
		foreach($data as $k => $v){
			$str .= '<option value="'.$v['region_id'].'">'.$v['region_name'].'</option>';
		}
		if(count($data)>0){
			$str = '<select style="width:auto; display:inline; margin-right:8px;" class="form-control" id="select" datatype="*" onchange="sendRegion(this)" name="area[]">'.$str.'</select>';
		}else{
			$str='';
		}
		echo $str;
	}
	
	public function setRegion(){
		$db=M('Region');
		
		$area = explode(',', trim($this->_post('area'),','));
		
		$ret = "";
		foreach($area as $skey => $sid){
			$father_id = $skey == 0 ? 0 : $area[$skey - 1];
			$data = $db->where(array('father_id'=>$father_id))->select();
			$str = '<option value="">-请选择-</option>';
			foreach($data as $k => $v){
				$selectstr = "";
				if($sid == $v['region_id']){
					$selectstr = 'selected="selected"'; 
				}
				$str .= '<option '.$selectstr.' value="'.$v['region_id'].'">'.$v['region_name'].'</option>';
			}
			if(count($data)>0){
				$str = '<select style="width:auto; display:inline; margin-right:8px;" class="form-control" id="select" datatype="*" onchange="sendRegion(this)" name="area[]">'.$str.'</select>';
			}else{
				$str='';
			}
			$ret .= $str;
		}
		
		echo $ret;
		
		
	}
	
	
	public function showLink(){
		$table = isset($_GET['table']) && $_GET['table'] != '' ? $_GET['table'] : 'Category';
		$this ->table = $table;
		$pid = isset($_GET['pid']) && $_GET['pid'] == '' ? intval($_GET['pid']) : 0;
		if($pid > 0){
			 $this->listmap .= " and pid = '".$pid."'";
		}
		if($table == 'Category' || $table == 'Product_category'){
			$this->listmap .= " and pid = '0'";
		}
		$this->dao = D($table);
		$this->_list();
		$list=$this->list;
		if($table == 'Category' || $table == 'Product_category'){
			foreach($list as $k=>$v){
			    $list[$k]['sub'] = $this->dao->getListToArray1($v['id'], $this->siteid);
		    }
		}
		$this->assign('list', $list);
		$this->display('Public:showLink');
	}
	
	public function showIcon(){
		//最近使用的图标
		$this->display('Public:icon');
	}
	
}